package com.example.lenovo.listvitesqlite;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements IOnDataChangeListener {
    private Button btnAdd;
    private ListView lv_stu;
    private ArrayList<Student> studentArrayList = new ArrayList<>();
    private StudentAdapter adapter;

    private EditText keyText;
    private ImageView search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findView();

        //测试、初始化学生列表
        //initStudentArrayList();

        adapter = new StudentAdapter(MainActivity.this,studentArrayList,MainActivity.this);

        //从数据库中获取数据、代替初始化学生列表
        readDataFromDB();

        lv_stu.setAdapter(adapter);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent,1001);
            }
        });
    }

    private void initStudentArrayList() {
        studentArrayList.add(new Student("1101","mike",100));
        studentArrayList.add(new Student("1102","mika",60));
        studentArrayList.add(new Student("1103","mikd",40));
    }

    private void findView() {
        lv_stu = findViewById(R.id.lv_stu);
        btnAdd = findViewById(R.id.btn_add);
        keyText = findViewById(R.id.keyText);
        search = findViewById(R.id.search);

        //打开新的添加学生的活动页面
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivityForResult(intent,1001);
            }
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String key = keyText.getText().toString();
                searchDataFromDB(key);
            }
        });

        //编辑功能 ListView点击事件
        lv_stu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //点了哪个学生就拿哪个学生的信息过去
                Student student = studentArrayList.get(i);
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,EditActivity.class);
                intent.putExtra("NO",student.getStuno());
                intent.putExtra("NAME",student.getName());
                intent.putExtra("AGE",student.getAge());

                startActivityForResult(intent,1002);

            }
        });
    }

    /**
     * 实现搜索功能  注意  数据库查询语句！！
     * @param key
     */
    private void searchDataFromDB(String key) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String where = "name like '"+ key +"' or stuno like '"+ key +"' or age like '"+ key +"'";
        studentArrayList.clear();
        Cursor cursor = db.query("student", null,where,null,null,
                null,null,null);

        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String stuname = cursor.getString(1);
                int stuAge = cursor.getInt(2);

                studentArrayList.add(new Student(stuno, stuname, stuAge));
            }
        }

        adapter.notifyDataSetChanged();

        cursor.close();
        db.close();

    }

    /**
     * 创建和打开数据库并且遍历数据表  注意   数据库创建表语句！！！！！！！！！！！！！！！！！！！
     * @return
     */
    private void readDataFromDB() {

        //数据库文件路径
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String sql = "create table if not exists student (stuno varchar(20), name varchar(20), age int)";
        db.execSQL(sql);

        studentArrayList.clear();
        Cursor cursor = db.query("student", null,null,null,null,
                null,null,null);

        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String stuname = cursor.getString(1);
                int stuAge = cursor.getInt(2);

                studentArrayList.add(new Student(stuno, stuname, stuAge));
            }
        }

        adapter.notifyDataSetChanged();

        cursor.close();
        db.close();
    }

    /*   *//**
     * 提取适配器返回来得数据 通过创建新对象并且添加到数据库
     * @param requestCode
     * @param resultCode
     * @param data
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == 2001){
            String stuno = data.getStringExtra("NO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);

            Student student = new Student(stuno, name, age);

            //将获得用户输入的信息并且创建好得学生添加到数据库里
            addStudentToDB(student);
        }

        if (resultCode == 2003){
            String stuno = data.getStringExtra("NO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE",0);

            Student student = new Student(stuno, name, age);
            updateStudentToDB(student);
        }

    }

    /**
     * 根据拿回用户编辑后的信息、修改数据库表信息   注意   数据库修改表内容语句！！！！！！！！！！！！！！！！！！！！
     * @param student
     */
    private void updateStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String sql = "update student set name = '"+ student.getName() +"', age = '"+ student.getAge() +"'" +
                "where stuno = '"+ student.getStuno() +"'";

        db.execSQL(sql);
        db.close();
        readDataFromDB();
    }

    private void addStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        ContentValues values = new ContentValues();
        values.put("stuno", student.getStuno());//字段名保持一致
        values.put("name", student.getName());
        values.put("age", student.getAge());

        //数据库插入信息
        db.insert("student", null, values);
        db.close();

        readDataFromDB();
    }

    /**
     * 删除学生   注意  数据库删除表内容语句！
     * @param student
     */
    @Override
    public void delStu(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        //第一种删除方法
        String sql = "delete from student where stuno = '"+ student.getStuno()+"'";
        db.execSQL(sql);

        //第二种方法
        /*String where = "stuno = '"+ student.getStuno()+"'";
        db.delete("student",where,null);*/

        db.close();
        readDataFromDB();
    }
}
